package com.waves.common.event.listener;

import com.waves.chat.dao.MessageDao;
import com.waves.common.event.UserBlackEvent;
import com.waves.user.cache.UserCache;
import com.waves.websocket.domain.enums.WSRespTypeEnum;
import com.waves.user.domain.vo.ws.WSBlack;
import com.waves.websocket.domain.vo.WSBaseVO;
import com.waves.websocket.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 用户拉黑监听器
 *
 * @author dlw
 */
@Slf4j
@Component
public class UserBlackListener {
    @Resource
    private MessageDao messageDao;
    @Resource
    private WebSocketService webSocketService;
    @Resource
    private UserCache userCache;

    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void refreshRedis(UserBlackEvent event) {
        // 清除相关的缓存，让拉黑立马生效
        userCache.evictBlackMap();
        userCache.remove(event.getUser().getId());
    }

    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void deleteMsg(UserBlackEvent event) {
        // 对该用户所有的消息都进行删除
        messageDao.invalidByUid(event.getUser().getId());
    }

    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void sendPush(UserBlackEvent event) {
        // 给所有在线用户推送用户拉黑事件
        Long uid = event.getUser().getId();
        WSBaseVO<WSBlack> resp = new WSBaseVO<>();
        WSBlack black = new WSBlack(uid);
        resp.setData(black);
        resp.setType(WSRespTypeEnum.BLACK.getType());
        webSocketService.sendToAllOnline(resp, uid);
    }


}
